/**
 * 角色属性点和装备系统测试脚本
 * 基于test-code-1338.js修改，专门测试属性点分配和装备管理功能
 * 不硬编码数据，通过WebSocket指令动态获取数据
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },

    // 测试用户信息
    testUser: {
        mobile: '17091271111',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e' // 123456的SHA256
    },

    // 测试角色信息
    testCharacter: {
        name: '属性测试角色',
        sex: 1, // 1:男, 0:女
        roleType: 1, // 1:武士, 2:文人, 3:异师
        headIndex: 2
    }
};

class CharacterAttributeEquipmentTester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.testResults = [];
        this.attributeData = null;
        this.equipmentData = null;
        this.availableEquipment = []; // 可用的装备列表
    }

    // 运行完整测试流程
    async runTest() {
        console.log('🚀 开始角色属性点和装备系统测试...\n');
        console.log('测试目标：HTTP登录 → WebSocket连接 → 选择角色 → 测试属性点分配 → 测试装备管理\n');

        try {
            // 1. HTTP登录
            await this.testHttpLogin();

            // 2. 建立WebSocket连接
            await this.testWebSocketConnection();

            // 3. 查询角色列表
            await this.testQueryCharacters();

            // 4. 如果没有角色，先创建角色
            if (this.characters.length === 0) {
                await this.testCreateCharacter();
                // 重新查询角色列表
                await this.testQueryCharacters();
            }

            // 5. 选择角色
            await this.testSelectCharacter();

            // 6. 测试属性点查询
            await this.testQueryAttributePoints();

            // 7. 测试属性点分配
            await this.testAllocateAttributePoints();

            // 8. 测试装备信息查询
            await this.testQueryEquipmentInfo();

            // 9. 查询可用装备
            await this.testQueryAvailableEquipment();

            // 10. 测试装备穿戴
            if (this.availableEquipment.length > 0) {
                await this.testEquipItem();
            }

            // 11. 测试装备卸下
            await this.testUnequipItem();

            // 12. 验证数据一致性
            await this.validateDataConsistency();

            // 13. 断开连接
            await this.testDisconnect();

            // 输出测试结果
            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    // 1. HTTP登录测试
    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');

        try {
            // 首先尝试注册用户（如果不存在）
            await this.registerUser();

            // 执行登录
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;

                console.log(`✅ 登录成功: userId=${this.userId}, token=${this.token.substring(0, 8)}...`);
                this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }

        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            this.addTestResult('HTTP登录', false, error.message);
            throw error;
        }
    }

    // 注册用户（如果不存在）
    async registerUser() {
        try {
            const res = await this.makeHttpRequest('/user-service/user/register', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.passwordHash,
                captcha: '123456' // 模拟验证码
            });
            console.log('📝 用户注册成功', res);
        } catch (error) {
            // 如果用户已存在，忽略错误
            if (error.message.includes('MOBILE_EXISTS') || error.message.includes('已存在')) {
                console.log('👤 用户已存在，跳过注册');
            } else {
                console.log('⚠️ 注册失败:', error.message);
            }
        }
    }

    // 2. WebSocket连接测试
    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');

        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    this.addTestResult('WebSocket连接', true, '连接建立成功');

                    // 设置消息监听器
                    this.setupMessageHandler();

                    // 等待连接完全稳定
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    this.addTestResult('WebSocket连接', false, error.message);
                    reject(error);
                });

                this.ws.on('close', () => {
                    console.log('🔌 WebSocket连接已关闭');
                });

                // 连接超时
                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);

            } catch (error) {
                reject(error);
            }
        });
    }

    // 设置消息处理器
    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));

                // 根据act_id处理不同类型的响应
                this.handleWebSocketResponse(message);

            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    // 处理WebSocket响应
    handleWebSocketResponse(message) {
        const { act_id, code, roleList, roleCount, data, msg } = message;

        switch (act_id) {
            case 3: // 查询角色列表响应
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                }
                break;

            case 4: // 角色选择响应
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                }
                break;

            case 5: // 角色创建响应（兼容格式）
                if (code === 0) {
                    console.log('🆕 角色创建成功');
                }
                break;

            case 390: // 角色创建响应（标准指令）
                if (code === 0) {
                    console.log('🆕 角色创建成功');
                }
                break;

            case 1005: // 属性点分配响应
                this.attributeData = {
                    act_id: message.act_id,
                    code: message.code,
                    data: message.data,
                    timestamp: new Date().toISOString()
                };
                console.log(`📊 属性点数据接收:`, JSON.stringify(this.attributeData, null, 2));
                break;

            case 1137: // 装备穿戴响应
                console.log(`⚔️ 装备穿戴结果:`, JSON.stringify(message, null, 2));
                break;

            case 1136: // 装备卸下响应
                console.log(`🛡️ 装备卸下结果:`, JSON.stringify(message, null, 2));
                break;

            case 1130: // 装备信息查询响应
                this.equipmentData = {
                    act_id: message.act_id,
                    code: message.code,
                    data: message.data,
                    timestamp: new Date().toISOString()
                };
                console.log(`📋 装备信息数据接收:`, JSON.stringify(this.equipmentData, null, 2));
                break;

            default:
                // 记录其他消息但不处理
                break;
        }
    }

    // 3. 查询角色列表
    async testQueryCharacters() {
        console.log('\n📋 步骤3: 查询角色列表...');

        return new Promise(async (resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('查询角色列表', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 等待WebSocket连接稳定
            await this.delay(1000);

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                            this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
                        } else {
                            // 即使没有角色，也算查询成功
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                            this.addTestResult('查询角色列表', true, '获取0个角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询角色列表', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送查询角色列表请求
            this.ws.send(JSON.stringify({
                c: 3,
                d: null
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('查询角色列表', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    // 4. 创建角色测试
    async testCreateCharacter() {
        console.log('\n🆕 步骤4: 创建角色测试...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('创建角色', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;
            let retryCount = 0;
            const maxRetries = 2;

            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    console.log(`📨 收到创建角色响应:`, JSON.stringify(message, null, 2));

                    if (message.act_id === 5 || message.act_id === 390) { // 兼容格式或标准指令
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 角色创建成功');
                            this.addTestResult('创建角色', true, '角色创建成功');

                            // 等待一段时间让服务器处理角色创建
                            setTimeout(() => {
                                resolve();
                            }, 2000);
                        } else {
                            const errorMsg = message.msg || '未知错误';
                            console.log(`❌ 角色创建失败: ${errorMsg}`);

                            // 如果是角色名重复，尝试使用不同的名字
                            if (errorMsg.includes('重复') || errorMsg.includes('已存在') || errorMsg.includes('DUPLICATE')) {
                                if (retryCount < maxRetries) {
                                    retryCount++;
                                    const newName = `${CONFIG.testCharacter.name}_${Date.now()}`;
                                    console.log(`🔄 角色名重复，尝试使用新名字: ${newName}`);

                                    // 重新发送创建角色请求
                                    setTimeout(() => {
                                        this.createCharacterWithName(newName, resolve);
                                    }, 1000);
                                    return;
                                }
                            }

                            this.addTestResult('创建角色', false, errorMsg);
                            resolve();
                        }
                    }
                } catch (error) {
                    console.error('❌ 创建角色响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('创建角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送创建角色请求
            this.createCharacterWithName(CONFIG.testCharacter.name, resolve);

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('创建角色', false, '请求超时');
                    resolve();
                }
            }, 15000);
        });
    }

    // 使用指定名字创建角色
    createCharacterWithName(name, resolve) {
        const createData = {
            c: 5, // 兼容格式
            d: {
                name: name,
                sex: CONFIG.testCharacter.sex,
                roleType: CONFIG.testCharacter.roleType,
                headIndex: CONFIG.testCharacter.headIndex
            }
        };

        console.log(`📤 发送创建角色请求:`, JSON.stringify(createData, null, 2));
        this.ws.send(JSON.stringify(createData));
    }

    // 5. 选择角色
    async testSelectCharacter() {
        console.log('\n🎯 步骤5: 选择角色...');

        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            this.addTestResult('选择角色', false, '没有可用角色');
            return;
        }

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('选择角色', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 选择第一个角色
            const targetCharacter = this.characters[0];

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.code === 0) {
                            this.selectedCharacter = targetCharacter;
                            console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
                            this.addTestResult('选择角色', true, `选择角色: ${targetCharacter.name}`);

                            // 等待服务器处理角色选择
                            setTimeout(() => {
                                resolve();
                            }, 2000);
                        } else {
                            console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('选择角色', false, message.msg || '选择失败');
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('选择角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送选择角色请求
            this.ws.send(JSON.stringify({
                c: 4,
                d: {
                    characterId: targetCharacter.id
                }
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('选择角色', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    // 6. 测试属性点查询
    async testQueryAttributePoints() {
        console.log('\n📊 步骤6: 测试属性点查询...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('属性点查询', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1005) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 属性点查询成功');
                            console.log(`📊 当前属性点数据:`, JSON.stringify(message.data, null, 2));

                            // 验证基础数据结构
                            if (message.data && typeof message.data === 'object') {
                                console.log('✅ 属性点数据结构验证通过');
                                this.addTestResult('属性点查询', true, '获取属性点数据成功');
                            } else {
                                console.log('❌ 属性点数据结构验证失败');
                                this.addTestResult('属性点查询', false, '返回数据格式错误');
                            }
                        } else {
                            console.log(`❌ 属性点查询失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('属性点查询', false, message.msg || '查询失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 属性点查询响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('属性点查询', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送属性点查询请求（查询当前状态）
            const requestData = {
                c: 1005,
                d: { ap: 0, hp: 0, mp: 0, sp: 0 } // 查询模式
            };

            console.log(`📤 发送属性点查询请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('属性点查询', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 7. 测试属性点分配
    async testAllocateAttributePoints() {
        console.log('\n⚡ 步骤7: 测试属性点分配...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('属性点分配', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1005) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 属性点分配成功');
                            console.log(`📊 分配后属性点数据:`, JSON.stringify(message.data, null, 2));

                            // 验证分配结果
                            if (message.data && typeof message.data === 'object') {
                                console.log('✅ 属性点分配结果验证通过');
                                this.addTestResult('属性点分配', true, '属性点分配成功');
                            } else {
                                console.log('❌ 属性点分配结果验证失败');
                                this.addTestResult('属性点分配', false, '分配结果格式错误');
                            }
                        } else {
                            console.log(`❌ 属性点分配失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('属性点分配', false, message.msg || '分配失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 属性点分配响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('属性点分配', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送属性点分配请求（分配1点给每个属性）
            const requestData = {
                c: 1005,
                d: { ap: 1, hp: 1, mp: 1, sp: 1 } // 分配模式
            };

            console.log(`📤 发送属性点分配请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('属性点分配', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 8. 测试装备信息查询
    async testQueryEquipmentInfo() {
        console.log('\n📋 步骤8: 测试装备信息查询...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('装备信息查询', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1130) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 装备信息查询成功');
                            console.log(`📋 当前装备信息:`, JSON.stringify(message.data, null, 2));

                            // 验证装备数据结构
                            if (message.data && typeof message.data === 'object') {
                                console.log('✅ 装备信息数据结构验证通过');
                                this.addTestResult('装备信息查询', true, '获取装备信息成功');
                            } else {
                                console.log('❌ 装备信息数据结构验证失败');
                                this.addTestResult('装备信息查询', false, '返回数据格式错误');
                            }
                        } else {
                            console.log(`❌ 装备信息查询失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('装备信息查询', false, message.msg || '查询失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 装备信息查询响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('装备信息查询', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送装备信息查询请求
            const requestData = {
                c: 1130,
                d: {}
            };

            console.log(`📤 发送装备信息查询请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('装备信息查询', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 9. 查询可用装备
    async testQueryAvailableEquipment() {
        console.log('\n🎒 步骤9: 查询可用装备...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('查询可用装备', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1267) { // 假设1267是查询装备背包的指令
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 可用装备查询成功');
                            console.log(`🎒 可用装备列表:`, JSON.stringify(message.data, null, 2));

                            // 保存可用装备列表
                            if (message.data && message.data.list && Array.isArray(message.data.list)) {
                                this.availableEquipment = message.data.list;
                                console.log(`📊 找到${this.availableEquipment.length}件可用装备`);
                                this.addTestResult('查询可用装备', true, `找到${this.availableEquipment.length}件装备`);
                            } else {
                                this.availableEquipment = [];
                                console.log('📊 暂无可用装备');
                                this.addTestResult('查询可用装备', true, '暂无可用装备');
                            }
                        } else {
                            console.log(`❌ 可用装备查询失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('查询可用装备', false, message.msg || '查询失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 可用装备查询响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询可用装备', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送查询可用装备请求
            const requestData = {
                c: 1267, // 假设这是查询装备背包的指令
                d: {}
            };

            console.log(`📤 发送查询可用装备请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询可用装备', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 10. 测试装备穿戴
    async testEquipItem() {
        console.log('\n⚔️ 步骤10: 测试装备穿戴...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('装备穿戴', false, 'WebSocket未连接');
            return;
        }

        if (this.availableEquipment.length === 0) {
            console.log('⚠️ 没有可用装备进行穿戴测试');
            this.addTestResult('装备穿戴', false, '没有可用装备');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1137) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 装备穿戴成功');
                            console.log(`⚔️ 穿戴结果:`, JSON.stringify(message.data, null, 2));
                            this.addTestResult('装备穿戴', true, '装备穿戴成功');
                        } else {
                            console.log(`❌ 装备穿戴失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('装备穿戴', false, message.msg || '穿戴失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 装备穿戴响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('装备穿戴', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 选择第一件可用装备进行穿戴
            const equipmentToEquip = this.availableEquipment[0];

            // 发送装备穿戴请求
            const requestData = {
                c: 1137,
                d: { id: equipmentToEquip.id }
            };

            console.log(`📤 发送装备穿戴请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('装备穿戴', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 11. 测试装备卸下
    async testUnequipItem() {
        console.log('\n🛡️ 步骤11: 测试装备卸下...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('装备卸下', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1136) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 装备卸下成功');
                            console.log(`🛡️ 卸下结果:`, JSON.stringify(message.data, null, 2));
                            this.addTestResult('装备卸下', true, '装备卸下成功');
                        } else {
                            console.log(`❌ 装备卸下失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('装备卸下', false, message.msg || '卸下失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 装备卸下响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('装备卸下', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送装备卸下请求（卸下武器，type=2）
            const requestData = {
                c: 1136,
                d: { type: 2 } // 武器类型
            };

            console.log(`📤 发送装备卸下请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('装备卸下', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 12. 验证数据一致性
    async validateDataConsistency() {
        console.log('\n🔍 步骤12: 验证数据一致性...');

        let validationResults = [];

        // 验证属性点数据
        if (this.attributeData && this.attributeData.data) {
            const attrValidation = this.validateAttributeData(this.attributeData.data);
            validationResults.push(attrValidation);
        }

        // 验证装备数据
        if (this.equipmentData && this.equipmentData.data) {
            const equipValidation = this.validateEquipmentData(this.equipmentData.data);
            validationResults.push(equipValidation);
        }

        // 统计验证结果
        const validCount = validationResults.filter(r => r.isValid).length;
        const totalCount = validationResults.length;

        console.log(`📊 数据一致性验证结果: ${validCount}/${totalCount} 项通过验证`);

        if (validCount === totalCount && totalCount > 0) {
            console.log('✅ 所有数据一致性验证通过');
            this.addTestResult('数据一致性验证', true, `所有${totalCount}项验证通过`);
        } else {
            console.log(`⚠️ 部分数据一致性验证失败: ${totalCount - validCount}项有问题`);
            this.addTestResult('数据一致性验证', false, `${validCount}/${totalCount}项验证通过`);
        }
    }

    // 验证属性点数据
    validateAttributeData(data) {
        const requiredFields = ['ap', 'hp', 'mp', 'sp', 'df', 'weight', 'maxHp', 'maxMp', 'maxWeight'];
        const missingFields = [];
        const invalidFields = [];

        // 检查必需字段
        requiredFields.forEach(field => {
            if (!(field in data)) {
                missingFields.push(field);
            }
        });

        // 检查字段类型
        if (data.ap !== undefined && typeof data.ap !== 'number') {
            invalidFields.push('ap应为数字类型');
        }
        if (data.hp !== undefined && typeof data.hp !== 'number') {
            invalidFields.push('hp应为数字类型');
        }
        if (data.mp !== undefined && typeof data.mp !== 'number') {
            invalidFields.push('mp应为数字类型');
        }
        if (data.sp !== undefined && typeof data.sp !== 'number') {
            invalidFields.push('sp应为数字类型');
        }

        const isValid = missingFields.length === 0 && invalidFields.length === 0;

        if (!isValid) {
            console.log(`❌ 属性点数据验证失败:`);
            if (missingFields.length > 0) {
                console.log(`   缺失字段: ${missingFields.join(', ')}`);
            }
            if (invalidFields.length > 0) {
                console.log(`   字段类型错误: ${invalidFields.join(', ')}`);
            }
        } else {
            console.log('✅ 属性点数据验证通过');
        }

        return {
            type: '属性点数据',
            isValid,
            missingFields,
            invalidFields
        };
    }

    // 验证装备数据
    validateEquipmentData(data) {
        const equipmentSlots = ['right_hand', 'body', 'head', 'neck', 'left_hand', 'foot'];
        let validSlots = 0;

        equipmentSlots.forEach(slot => {
            if (data[slot] === null || (data[slot] && typeof data[slot] === 'object')) {
                validSlots++;
            }
        });

        const isValid = validSlots === equipmentSlots.length;

        if (!isValid) {
            console.log(`❌ 装备数据验证失败: ${validSlots}/${equipmentSlots.length} 个槽位数据有效`);
        } else {
            console.log('✅ 装备数据验证通过');
        }

        return {
            type: '装备数据',
            isValid,
            validSlots,
            totalSlots: equipmentSlots.length
        };
    }

    // 13. 断开连接
    async testDisconnect() {
        console.log('\n🔌 步骤13: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
        this.addTestResult('断开连接', true, '连接已断开');
    }

    // 添加测试结果
    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    // 打印测试结果
    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！');
        } else {
            console.log('⚠️  部分测试失败，请检查日志');
        }

        // 输出系统功能分析
        console.log('\n📋 系统功能分析:');
        console.log('='.repeat(50));

        if (this.attributeData && this.attributeData.data) {
            console.log('属性点系统:');
            console.log(`  当前攻击力: ${this.attributeData.data.ap || 'N/A'}`);
            console.log(`  当前气血: ${this.attributeData.data.hp || 'N/A'}`);
            console.log(`  当前精力: ${this.attributeData.data.mp || 'N/A'}`);
            console.log(`  当前速度: ${this.attributeData.data.sp || 'N/A'}`);
            console.log(`  剩余属性点: ${this.attributeData.data.p || 'N/A'}`);
        }

        if (this.equipmentData && this.equipmentData.data) {
            console.log('装备系统:');
            const slots = ['right_hand', 'body', 'head', 'neck', 'left_hand', 'foot'];
            slots.forEach(slot => {
                const equipment = this.equipmentData.data[slot];
                if (equipment) {
                    console.log(`  ${slot}: ${equipment.name || 'N/A'} (等级: ${equipment.lvl || 'N/A'})`);
                } else {
                    console.log(`  ${slot}: 未装备`);
                }
            });
        }

        console.log(`可用装备数量: ${this.availableEquipment.length}`);
    }

    // HTTP请求工具方法
    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, (res) => {
                let body = '';

                res.on('data', (chunk) => {
                    body += chunk;
                });

                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            if (data) {
                req.write(JSON.stringify(data));
            }

            req.end();
        });
    }

    // 延迟函数
    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 运行测试
async function main() {
    const tester = new CharacterAttributeEquipmentTester();
    await tester.runTest();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = CharacterAttributeEquipmentTester;
